package com.fingard.dsp.bank.directbank.hfrcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.abc23.util.StringHelper;
import com.fingard.net.WebRequest;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * Created by F on 2020/2/4.
 */
public class HFRCB01Base extends DirectBase {

    protected static TransIDHelper idHelper = new TransIDHelper(1,9999);
    protected String getBatchID(Date date){
        return Format.DateTime14Format.format(date)+idHelper.getNextIDStr();
    }


    protected void writeCommonHeader(XmlTextWriter xmlWriter, HFRCB01Header p_bankHeader) throws Exception{
        if(StringHelper.isNullOrEmpty(p_bankHeader.trsCode))
        {
            throw new Exception("未赋值接口代码TrsCode");
        }
        if(p_bankHeader.reqTime==null)
        {
            throw new Exception("未赋值交易时间ReqTime");
        }
        if(StringHelper.isNullOrEmpty(p_bankHeader.serialNo))
        {
            throw new Exception("未赋值交易流水号SerialNo");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\" ?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("SerialNo",p_bankHeader.serialNo );
        xmlWriter.writeElementString("ReqTime", Format.DateTime14Format.format(p_bankHeader.reqTime));
        xmlWriter.writeElementString("TrsCode", p_bankHeader.trsCode);
        xmlWriter.writeEndElement();
    }

    protected String getCharset(){
        return getBankConfig().getCharset("GBK");
    }

    protected String[] sendToBank(String p_reqStr, boolean isSign) throws UnsupportedEncodingException {
        String[] retStr = new String[]{"",""};
//        /bweb/b2econnect.do?userPassword=111111&SIGDATA=0
        String tmpUrl = bankFront.serverURL+"?userPassword=" + bankFront.loginPasswd + "&SIGDATA=" + (isSign?"1":"0") ;
        WriteBankLogLn("2.提交银行的地址：" + tmpUrl);
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(100000);
        tmpWebRequest.setRequestProperty("Content-Type", "text/xml");
        tmpWebRequest.setRequestProperty("connection", "Close");

        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
}
